package chances.epg.user.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.type.TypeReference;

import chances.epg.commons.log.EpgLogFactory;
import chances.epg.commons.utils.DateUtils;
import chances.epg.commons.utils.JSONUtils;
import chances.epg.commons.utils.RequestUtils;
import chances.epg.data.PageBean;
import chances.epg.entity.user.UserHistory;
import chances.epg.user.service.HistoryService;

@RestController
@RequestMapping(value = "/history")
public class HistoryController extends UserAbstractController {
	private static Logger logger = EpgLogFactory.getSystemLogger();

	@Autowired
	private HistoryService historyService;

	@RequestMapping(value = "/add")
	public UserResultResponse<UserHistory> addHistory(ModelMap model, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		UserHistory history = this.createUserHistory(request);
		UserResultResponse<UserHistory> result = new UserResultResponse<UserHistory>();
		result.setResult(history);
		result.setStatus(SUCCESS);
		// 参数检查
		if (StringUtils.isBlank(history.getUserId()) || StringUtils.isBlank(history.getContentId())) {
			result.setStatus(VALID_PARAM);
		} else {
			try {
				this.historyService.addUserHistory(history);
			} catch (Throwable ex) {
				result.setStatus(DB_ERROR);
				logger.error("add user history error.", ex);
			}
		}

		return result;
	}

	@RequestMapping(value = "/remove")
	public UserResultResponse<UserHistory> removeHistory(ModelMap model, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String userId = RequestUtils.getParameter(request, "userId", "");
		String contentId = RequestUtils.getParameter(request, "contentId", "");
		UserResultResponse<UserHistory> result = new UserResultResponse<UserHistory>();
		result.setStatus(SUCCESS);
		// 参数检查
		if (StringUtils.isBlank(userId) || StringUtils.isBlank(contentId)) {
			result.setStatus(VALID_PARAM);
		} else {
			try {
				this.historyService.removeUserHistory(userId, contentId);
			} catch (Throwable ex) {
				result.setStatus(DB_ERROR);

				logger.error("remove user history error.", ex);
			}

		}

		return result;
	}

	@RequestMapping(value = "/removeHistories")
	public UserResultResponse<UserHistory> removeHistories(@RequestBody String body, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		UserResultResponse<UserHistory> result = new UserResultResponse<UserHistory>();
		result.setStatus(SUCCESS);

		try {
			List<UserHistory> userHistories = JSONUtils.toObject(body, new TypeReference<List<UserHistory>>() {
			});

			for (UserHistory userHistory : userHistories) {
				if (StringUtils.isNotBlank(userHistory.getUserId())
						&& StringUtils.isNotBlank(userHistory.getContentId()))
					this.historyService.removeUserHistory(userHistory.getUserId(), userHistory.getContentId());
			}

		} catch (Throwable ex) {
			result.setStatus(SYS_ERROR);
			logger.error("remove user collections error.", ex);
		}

		return result;
	}

	@RequestMapping(value = "/clear")
	public UserResultResponse<UserHistory> clearHistory(ModelMap model, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String userId = RequestUtils.getParameter(request, "userId", "");
		String category = RequestUtils.getParameter(request, "category", "");
		UserResultResponse<UserHistory> result = new UserResultResponse<UserHistory>();
		result.setStatus(SUCCESS);
		// 参数检查
		if (StringUtils.isBlank(userId)) {
			result.setStatus(VALID_PARAM);
		} else {
			try {
				this.historyService.clearUserHistories(userId, category);
			} catch (Throwable ex) {
				result.setStatus(DB_ERROR);

				logger.error("clear user history error.", ex);
			}
		}
		return result;
	}

	@RequestMapping(value = "/get")
	public UserResultResponse<UserHistory> getHistory(ModelMap model, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String userId = RequestUtils.getParameter(request, "userId", "");
		String contentId = RequestUtils.getParameter(request, "contentId", "");
		UserResultResponse<UserHistory> result = new UserResultResponse<UserHistory>();
		result.setStatus(SUCCESS);
		// 参数检查
		if (StringUtils.isBlank(userId) || StringUtils.isBlank(contentId)) {
			result.setStatus(VALID_PARAM);

		} else {
			try {
				UserHistory userHistory = this.historyService.getUserHistory(userId, contentId);
				result.setResult(userHistory);
			} catch (Throwable ex) {
				result.setStatus(DB_ERROR);

				logger.error("get user history error.", ex);
			}
		}

		return result;
	}

	@RequestMapping(value = "/list")
	public UserResultSetResponse<UserHistory> listHistory(ModelMap model, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String userId = RequestUtils.getParameter(request, "userId", "");
		String contentType = RequestUtils.getParameter(request, "contentType", "");
		String category = RequestUtils.getParameter(request, "category", "");
		UserResultSetResponse<UserHistory> result = new UserResultSetResponse<UserHistory>();
		result.setStatus(SUCCESS);
		// 参数检查
		if (StringUtils.isBlank(userId)) {
			result.setStatus(VALID_PARAM);
			return result;
		}

		PageBean page = this.getPageBean(request);
		Date beginTime = null;
		String strBeginTime = request.getParameter("beginTime");
		if (StringUtils.isNotBlank(strBeginTime)) {
			beginTime = DateUtils.toDateTime(strBeginTime);
		}

		Date endTime = null;
		String strEndTime = request.getParameter("endTime");
		if (StringUtils.isNotBlank(strEndTime)) {
			endTime = DateUtils.toDateTime(strEndTime);
		}

		try {
			List<UserHistory> historyList = this.historyService.listUserHistories(userId, contentType, category,
					beginTime, endTime, page);
			result.setResultSet(historyList);
			result.setPageBean(page);
		} catch (Throwable ex) {
		    logger.info(ex.getMessage(),ex);
			result.setStatus(DB_ERROR);

		}

		return result;
	}

	private UserHistory createUserHistory(HttpServletRequest request) {
		UserHistory history = new UserHistory();
		history.setContentId(RequestUtils.getParameter(request, "contentId", ""));
		history.setContentName(RequestUtils.getParameter(request, "contentName", ""));
		history.setContentPoster(RequestUtils.getParameter(request, "contentPoster", ""));
		history.setContentType(RequestUtils.getParameter(request, "contentType", ""));
		history.setElapsedTime(RequestUtils.getParameter(request, "elapsedTime", 0));
		history.setEpisodeIndex(RequestUtils.getParameter(request, "episodeIndex", 0));
		history.setPath(RequestUtils.getParameter(request, "path", ""));
		history.setProgramId(RequestUtils.getParameter(request, "programId", ""));
		history.setUserId(RequestUtils.getParameter(request, "userId", ""));
		history.setCategory(RequestUtils.getParameter(request, "category", ""));
		return history;
	}
}
